package com.flute.framework.index;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

import com.flute.framework.index.IFileIndexCounter;

public class LuceneFileIndexCounter implements IFileIndexCounter {

	@Override
	public int countRecord(String path) {

		IndexSearcher searcher = null;
		int count = 0;
		File file = new File(path);
		try {
			searcher = new IndexSearcher(FSDirectory.open(file));

			TopDocs tds = searcher.search(new MatchAllDocsQuery(), 10);
			count = tds.totalHits;
		} catch (CorruptIndexException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException("打开文件'" + file.getAbsolutePath()
					+ "'错误:" + e);
		} finally {
			IOUtils.closeQuietly(searcher);
		}

		return count;
	}
}
